/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.job.task.tms;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.renren.common.utils.Constant;
import io.renren.modules.job.task.ITask;
import io.renren.modules.tms.dao.ShipmentMapper;
import io.renren.modules.tms.entity.ShipmentError;
import io.renren.modules.tms.entity.ShipmentErrorReturn;
import io.renren.modules.tms.service.ShipmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 顺达有错误的接口上报
 */
@Component("ShunFengTask")
@Service
public class ShunDaShipmentTask implements ITask {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private ShipmentMapper shipmentMapper;

    @Override
    public void run(String params) {
        logger.debug("TestTask定时任务正在执行，参数为：{}", params);
        new Thread(() -> {
            String startDay = simpleDateFormat.format(new Date(DateUtil.offsetDay(new Date(), -1).getTime()));
            String endDay = simpleDateFormat.format(new Date());
//            uploadShipment(params);
        }).start();
    }

    public List<ShipmentErrorReturn> getErrorShipment(Map<String, Object> params){
        return uploadShipment(params);
    }

    protected List<ShipmentErrorReturn> uploadShipment(Map<String, Object> params) {

        // 根据承运商运单返回运单合集，通过插入时间筛选
        List<ShipmentError> shipmentList = shipmentMapper.selectErrorShipment(params);

        // 无数据
        if (CollectionUtils.isEmpty(shipmentList)) {
            return null;
        }

        // 以运单ID + 订单ID来去重遍历去重
        HashMap<String, ShipmentErrorReturn> returnMap = new HashMap<>();
        for (ShipmentError shipment : shipmentList) {
            if (shipment == null) {
                continue;
            }
            ShipmentErrorReturn shipmentErrorReturn = null;
            String key = shipment.getSHIPMENT_NO() + shipment.getORDER_NO();
            if (!returnMap.containsKey(key)) {
                shipmentErrorReturn = new ShipmentErrorReturn();
                shipmentErrorReturn.setShipmentNo(shipment.getSHIPMENT_NO());
                shipmentErrorReturn.setOrderNo(shipment.getORDER_NO());
                shipmentErrorReturn.setJdeNo(shipment.getJDE_NO());
                shipmentErrorReturn.setSectionId(String.valueOf(shipment.getSECTION_ID()));
                shipmentErrorReturn.setOriginCode(shipment.getORIGIN_CODE());
                shipmentErrorReturn.setOriginName(shipment.getORIGIN_NAME());
                shipmentErrorReturn.setDestCode(shipment.getDEST_CODE());
                shipmentErrorReturn.setDestName(shipment.getDEST_NAME());
                shipmentErrorReturn.setOrganizationCode(shipment.getORGANIZATION_CODE());
                shipmentErrorReturn.setOrganizationName(shipment.getORGANIZATION_NAME());
                shipmentErrorReturn.setReceiveOrganizationName(shipment.getRECEIVE_DEALERNAME());
                shipmentErrorReturn.setInsertDate(shipment.getSECTION_INSERT_DATE());
                shipmentErrorReturn.setCarrierShipmentNo(shipment.getCARRIER_SHIPMENT_NO());
                shipmentErrorReturn.setCarrierName(shipment.getCARRIER_NAME());
                shipmentErrorReturn.setShipmentStatus(shipment.getSHIPMENT_STATUS());
                returnMap.put(key, shipmentErrorReturn);
            } else {
                shipmentErrorReturn = returnMap.get(key);
            }

            // 没有查询到关联的订单
            if (StringUtils.isBlank(shipment.getSHIPMENT_NO())) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_01);
                continue;
            }
            // 接口没有回传，运单跟订单还没有绑定
            if (shipment.getSHIP_MID_ID() == null) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_01);
                continue;
            }
            // 出发事件没有回传
            if (shipment.getEVENT_ID_1() == null) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_03);
                continue;
            }
            // 出发事件处理失败
            if (shipment.getEVENT_SUCCESS_DATE_1() == null) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_04);
                continue;
            }
            // 到达事件没有回传
            if (shipment.getEVENT_ID_2() == null) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_05);
                continue;
            }
            // 到达事件处理失败
            if (shipment.getEVENT_SUCCESS_DATE_2() == null) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_06);
                continue;
            }
            // 签收事件没有回传
            if (shipment.getPOD_ID() == null) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_07);
                continue;
            }
            if ("E".equals(shipment.getRECEPIT_PROCESS_FLAG())) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_08);
                shipmentErrorReturn.setErrorDetail(shipment.getRECEPIT_PROCESS_MSG());
                continue;
            }
            String shipmentStatus = shipment.getSHIPMENT_STATUS();
            String orderStatus = shipment.getORDER_STATUS();
            // 运单与订单状态检查
            if (Constant.SHIPMENT_STATUS.TYPE_10.equals(shipmentStatus)) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_01);
                continue;
            }
            boolean isFail = (Constant.SHIPMENT_STATUS.TYPE_20.equals(shipmentStatus) && !Constant.ORDER_STATUS.TYPE_30.equals(orderStatus))
                    || (Constant.SHIPMENT_STATUS.TYPE_30.equals(shipmentStatus) && !Constant.ORDER_STATUS.TYPE_35.equals(orderStatus))
                    || (Constant.SHIPMENT_STATUS.TYPE_40.equals(shipmentStatus) && !Constant.ORDER_STATUS.TYPE_36.equals(orderStatus) && !Constant.ORDER_STATUS.TYPE_40.equals(orderStatus))
                    || (Constant.SHIPMENT_STATUS.TYPE_50.equals(shipmentStatus) && !Constant.ORDER_STATUS.TYPE_50.equals(orderStatus))
                    || (Constant.SHIPMENT_STATUS.TYPE_60.equals(shipmentStatus) && !Constant.ORDER_STATUS.TYPE_60.equals(orderStatus));
            if (isFail) {
                shipmentErrorReturn.setErrorType(Constant.INTERFACE_ERROR_TYPE.ERROR_09);
                String msg = String.format("存在运单为【%s】，订单状态为【%s】，状态不一致", shipmentStatus, orderStatus);
                shipmentErrorReturn.setErrorDetail(msg);
                continue;
            }
        }

        List<ShipmentErrorReturn> shipmentErrorList = new ArrayList<>();
        for (String key : returnMap.keySet()) {
            ShipmentErrorReturn shipmentError = returnMap.get(key);
            if (shipmentError == null || StringUtils.isBlank(shipmentError.getErrorType())) {
                continue;
            }
            shipmentErrorList.add(shipmentError);
        }

        // 按运单事件倒序排列
        Collections.sort(shipmentErrorList);

        String yichangleixing = (String) params.get("yichangleixing");

        // 如果运单异常条件过滤生效
        if (!StringUtils.isBlank(yichangleixing)) {
            shipmentErrorList = shipmentErrorList.stream().filter(shipmentErrorReturn -> {
                return yichangleixing.equals(shipmentErrorReturn.getErrorType());
            }).collect(Collectors.toList());
        }

        return shipmentErrorList;
    }

}
